package com.quotientintelligence.webdev.caftrak;


import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;


import com.quotientintelligence.PMF;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.quotientintelligence.caftrak.shared.CoffeeShop;
import com.quotientintelligence.caftrak.shared.ConsumptionEvent;
import com.quotientintelligence.caftrak.shared.ProductFactory;
import com.quotientintelligence.caftrak.shared.Substance;

@SuppressWarnings("serial")
public class Consume extends HttpServlet {
    private static final Logger log = Logger.getLogger(Consume.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        String content = req.getParameter("substance");
        if (content == null) {
            content = "Coffee";
        }
        int quantity = Integer.parseInt(req.getParameter("quantity"));

		ProductFactory myLocalStarbucks = new CoffeeShop();
		Substance sb = myLocalStarbucks.getAFix(content,quantity);
		

		Date date = new Date();
		ConsumptionEvent dr = new ConsumptionEvent(user,sb,date);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			pm.makePersistent(dr);
		}
		catch (Exception e){
			log.log(Level.ALL, e.getMessage());
		}
		finally
		{
			pm.close();
		}

        resp.sendRedirect("/getHistory.jsp");
    }
}